package org.midy.infrastructure;

import org.midy.infrastructure.customer.OnlineList;
import org.midy.infrastructure.tools.Logger;

import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * 业务路由分发总线接口的默认实现
 * InformationDistribution: 消息路由接口
 *
 */
public class DefaultInformationDistribution implements InformationDistribution {
    public static final Charset UTF8 = StandardCharsets.UTF_8;
    public static final Charset GBK = Charset.forName("GBK");
    @Override
    public void routeData(byte[] message, SocketChannel socketChannel, SelectionKey selectionKey, IOEventDrivenWorker worker) {
        String address = "";
        try {
            address = socketChannel.getRemoteAddress().toString();
        } catch (Throwable throwable) {
            Logger.warn("获取RemoteAddress失败：%s", throwable.getMessage());
        }
        address = address == null? "momo" : address.substring(1, address.length());
        String msg = "来自["+ address +"]的消息\r\n 【^_^】:\t" + (new String(message, UTF8)) + "\r\n";
        Logger.message(msg);
        OnlineList.broadcastMessage(msg.getBytes(UTF8));
    }

    @Override
    public void writeData(byte[] writeMessage, SocketChannel socketChannel, SelectionKey selectionKey, IOEventDrivenWorker worker) {
        worker.register(socketChannel, selectionKey, SelectionKey.OP_WRITE, writeMessage);
    }
}
